package com.webmeeting.chat.wordchat.events;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Date;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;

import com.myframework.utils.logutil.WMLogger;
import com.webmeeting.chat.wordchat.servlets.WordChatInitServlet;

public class WordChatMessageInbound extends MessageInbound {

	private String	username;

	@Override
	protected void onBinaryMessage(ByteBuffer byteBuffer) throws IOException {
		// Do nothing here for now
		return;
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onTextMessage(CharBuffer msg) throws IOException {
		for (WordChatMessageInbound user : WordChatInitServlet.getOnlineUserList()) {
			Date date = new Date();
			String time = date.getYear() + 1900 + "-" + date.getMonth() + "-" + date.getDay() + " " + date.getHours() + ":" + date.getMinutes() + ":"
					+ date.getSeconds();
			String message = this.username + " " + time + "\n" + msg.toString();
			CharBuffer buffer = CharBuffer.wrap(message);
			WMLogger.debug(buffer.toString());
			WsOutbound out = user.getWsOutbound();
			out.writeTextMessage(buffer);
			out.flush();
		}
	}

	@Override
	protected void onClose(int status) {
		WordChatInitServlet.removeOnlineUser(this);
		super.onClose(status);
	}

	@Override
	protected void onOpen(WsOutbound outbound) {
		super.onOpen(outbound);
		WordChatInitServlet.addOnlineUser(this);
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

}
